$(function() {
    //设置默认时间为当天
    $('#start_datetime').datepicker('setValue', $('#start_datetime').data('init') || new Date().format('yyyy-MM-dd'));

    //自动填入当天价格
    $('#stockId').on('change', function() {
        var stockNoName=  $('#stockId').find("option:selected").text();
        stockNo=stockNoName.split(" ")[0];
        $.get("/smtool_project/wxapp/api/stock/getRealPrice?stockCode="+stockNo,function(repdata,status){
            $('#importPrice').val(repdata);
            $('#importPrice').focus();
        });
        $.get('stock/'+stockNo,function (result) {
            if (result && result.exist){
                $('#dump_stock').show();
            }else{
                $('#dump_stock').hide();
            }
        });
    });

    //附件上传
    $('#doc-form-file').on('change', function() {
        var fileNames = [];
        $.each(this.files, function() {
            fileNames.push(this.name);
        });
        $('input[name=attachmentName]').val(fileNames.join());
        if (fileNames.length>0){
            $('input[name=attachmentName]').removeAttr('readonly');
        }else{
            $('input[name=attachmentName]').attr('readonly','readonly');
        }
    });

    //保存功能
    $('#a_save').on('click', function() {
        var importPrice=  $('#importPrice').val();
        var expectPrice= $('#expectPrice').val();
        var expectRate=  getExpectRate(importPrice,expectPrice);

        $('#expectRate').val(toDecimal(expectRate));
        $('#save').click();
    });

    //推荐公司列表
    $(".company-data-ajax").select2({
        ajax: {
            url: "../../api/dicStock/getStockList",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    name: params.term
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;
                var newdata = $.map(data.obj, function (obj) {
                    obj.id = obj.id || obj.rowId; // replace pk with your identifier
                    obj.text = obj.text ||obj.stockCode+" "+ obj.name;
                    return obj;
                });

                return {
                    results: newdata,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        placeholder:"请选择上市公司",
        minimumInputLength: 2
    });

    initStockPoolGroup(stockPoolGroupRender);

});

function initStockPoolGroup(cb){
    $.ajax({
            url : 'listStockPoolGroup',
            type : 'POST',
            data : { parentId:'0' },
            tryCount : 0,
            retryLimit : 3,
            success : function(res) {
                cb(res.obj || []);
            },
            error : function(xhr, textStatus, errorThrown ) {
                if (textStatus == 'timeout') {
                    this.tryCount++;
                    if (this.tryCount <= this.retryLimit) {
                        $.ajax(this);
                        return;
                    }
                    return;
                }
            }
          });
}

function stockPoolGroupRender(list){

    $('#parentPoolId').select2({
        placeholder: "请选择一级股票池",
        data: convertOptions(list),
        allowClear: true
    });

    initPoolGroupLevel2((stockpool.parentPoolId && getChildrenOptions(list,stockpool.parentPoolId))||[],function () {
        if (stockpool.childPoolId){
            $('#childPoolId').val(stockpool.childPoolId);
        }
    });

    $('#parentPoolId').on('change',function (e){
        $("#childPoolId option:gt(0)").remove();
        initPoolGroupLevel2(getChildrenOptions(list,e.target.value));
    });
}

function initPoolGroupLevel2(children,cb){
    children = children || [];
    $('#childPoolId').select2({
        placeholder: "请选择二级股票池",
        allowClear: true,
        data:children
    });
    if(children.length>0){
        $('#childPoolId').parent().show();
    }else{
        $('#childPoolId').parent().hide();
    }
    typeof cb === 'function' && cb();
}

function convertOptions(list){
    var options = [],i;
    for (i=0;i<list.length;i++){
        options.push({id:list[i].id,text:list[i].name});
    }
    return options;
}

function getChildrenOptions(list,parentPoolId){
    var i,options=[];
    if(parentPoolId.length==0) return options;
    for (i=0;i<list.length;i++){
        if (list[i].id == parentPoolId){
            var children = list[i].children || [];
            if (children.length>0){
               options = convertOptions(children);
            }
            break;
        }
    }
    return options;
}

function getExpectRate(importPrice,expectPrice) {
    return expectPrice==""?expectPrice:(expectPrice-importPrice)*100/importPrice
}

function toDecimal(x) {
    var f = parseFloat(x);
    if (isNaN(f)) return "";
    f = Math.round(x*100)/100;
    return f+"%";
}
